package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.UserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
import java.util.Enumeration;
import java.util.UUID;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private ResourceLoader resourceLoader;

    /**
     * 注册用户
     * @param username       用户名
     * @param nickname       昵称
     * @param password       密码
     * @param passwordRepeat 用户名不重复时,向用户表插入一条数据
     */
    @PostMapping("/register")
    public AppResult register(String username, String nickname, String password, String passwordRepeat) {
        if (StringUtil.isEmpty(username) ||
                StringUtil.isEmpty(nickname) ||
                StringUtil.isEmpty(passwordRepeat) ||
                !password.equals(passwordRepeat)) {
            log.info("校验失败");
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        log.info("校验成功");
        //2、如果参数没有问题我们就可以做一些准备工作
        //因为是要创建普通用户，所以需要参数user,根据需求初始化user对象，比如密码加盐
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(password, salt);
        // 2.3设置密码
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        // 3.调⽤Service
        userService.createNormalUser(user);
        // 4.返回
        return AppResult.success();

    }

    /**
     * 登录功能
     *
     * @param request  为什么会用到这个参数呀？
     * @param username
     * @param password
     */
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request, String username, String password) {

        User user = userService.login(username, password);
        //获取Session
        HttpSession session = request.getSession(true);
        //把User设置到Session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        //登录成功响应
        return AppResult.success();
    }

    /**
     * 退出登录
     *
     * @param request 会好汉sessionId
     * @return
     */
    @RequestMapping("/logout")
    public AppResult login(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session==null){
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        if (session != null) {
            //注销session
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            session.invalidate();
        }
        return AppResult.success();
    }

    /**
     * 展示用户信息
     *
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request, Long id) {
        User user = null;
        if (id == null) { //说明已经登陆，查询的是自己的信息
            HttpSession session = request.getSession(false);
            if(session==null){
                return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
            }
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else { //说没有有登录，查询的是被人的信息
            user = userService.selectById(id);
        }
        return AppResult.success(user);
    }

    /**
     * 修改用户信息，不包括头像和密码，头像和密码的修改需要单独设置接口！
     *
     * @param request
     * @param temp
     * @return
     */
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request, User temp) {
        //只能改自己的信息，所以对象可以从session获得
        HttpSession session = request.getSession(false);
        if (session == null) {
            //没有登陆
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        user.setUsername(temp.getUsername());
        user.setNickname(temp.getNickname());
        user.setGender(temp.getGender());
        user.setEmail(temp.getEmail());
        user.setPhoneNum(temp.getPhoneNum());
        user.setRemark(temp.getRemark());
        Date date = new Date();
        user.setUpdateTime(date);
        int ret = userService.modifyInfo(user);
        if (ret != 1) {
            return AppResult.failed(ResultCode.FAILED);
        }
        //更新之后的用户
        user = userService.selectById(user.getId());
        //把最新的⽤⼾信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success(user);
    }

    /**
     * 修改密码
     *
     * @param request
     * @param oldPassword
     * @param newPassword
     * @param passwordRepeat
     * @return
     */
    @PostMapping("/modifyPwd")
    public AppResult modifyPwd(HttpServletRequest request, String oldPassword, String newPassword, String passwordRepeat) {
        if (StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(passwordRepeat) || !newPassword.equals(passwordRepeat)) {
        }
        HttpSession session = request.getSession(false);
        if (session == null) {
            //没有登陆
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        int ret = userService.modifyPassword(user.getId(), newPassword, oldPassword);
        if (ret != 1) {
            return AppResult.failed(ResultCode.FAILED);
        }
        // 4.销毁 session ，意思是说需要重新登陆
        if (session != null) {
            session.invalidate();
        }
        return AppResult.success();
    }

    /**
     * 本地使用这个可以正常运行了
     */
    @PostMapping("/modifyProfilePicture2")
    // 处理上传头像的逻辑
    public AppResult modifyProfilePicture2(HttpServletRequest request,MultipartFile profilePicture) {

        HttpSession session = request.getSession(false);
        if(session==null) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user==null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        if (!profilePicture.isEmpty()) {
            try {
                //旧头像的相对路径
                String oldPicturePath = user.getAvatarUrl();
                //唯一的文件名
                String fileName = UUID.randomUUID().toString();
                //文件后缀
                String fileExtension = profilePicture.getOriginalFilename().substring(profilePicture.getOriginalFilename().lastIndexOf("."));
                //完整的文件名
                fileName = fileName+fileExtension;
                ClassLoader classLoader = getClass().getClassLoader();
                File file = new File(classLoader.getResource("").getFile());
                String basePath = file.getAbsolutePath();
                // 删除旧头像
                if (oldPicturePath != null && !oldPicturePath.isEmpty()) {
                    // 构造旧头像文件的完整路径
                    String oldPictureFullPath = basePath + File.separator + "static" + File.separator + oldPicturePath;
                    File oldPictureFile = new File(oldPictureFullPath);

                    // 判断旧头像文件是否存在并删除
                    if (oldPictureFile.exists()) {
                        if (oldPictureFile.delete()) {
                            System.out.println("旧头像删除成功！");
                        } else {
                            System.out.println("旧头像删除失败！");
                        }
                    }
                }
                //保存图片的完整径
                String fullFilePath = basePath + File.separator + "static"+File.separator+"headPortrait" +File.separator+fileName;
                System.out.println("fullFilePath+"+fullFilePath);

                //保存图片
                File destFile = new File(fullFilePath);
                profilePicture.transferTo(destFile);

                //把这个路径保存下来！
                user.setAvatarUrl("headPortrait/"  + fileName);
                userService.modifyInfo(user);

                //更新之后的用户
                user = userService.selectById(user.getId());
                //把最新的⽤⼾信息设置到session中
                session.setAttribute(AppConfig.USER_SESSION, user);

                return AppResult.success();
            } catch (Exception e) {
                e.printStackTrace();
                return AppResult.failed(ResultCode.FAILED);
            }
        } else {
            return AppResult.failed(ResultCode.FAILED);
        }
    }

    /**
     * 云服务器
     * 使用ResourceLoader获取路径,线上版本因为要使用的图片是外部资源，路径与本地不一致
     */
    @PostMapping("/modifyProfilePicture")
    public AppResult modifyProfilePicture(HttpServletRequest request,MultipartFile profilePicture) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if (!profilePicture.isEmpty()) {
            try {
                //唯一的文件名  //文件后缀
                String fileName = (UUID.randomUUID())
                        +profilePicture.getOriginalFilename().substring(profilePicture.getOriginalFilename().lastIndexOf("."));;
                String oldPicturePath = user.getAvatarUrl();
                //获取当前路径
                String currentPath = System.getProperty("user.dir");
                String targetFolderPath = currentPath + "/headPhoto/";
                //判断文件是否存在！
                File targetFolder = new File(targetFolderPath);
                if (!targetFolder.exists()) {
                    targetFolder.mkdirs();
                }
                // 删除旧头像
                if (oldPicturePath != null && !oldPicturePath.isEmpty()) {
                    // 构造旧头像文件的完整路径
                    String oldPictureFullPath = currentPath + File.separator + "headPhoto/"+ oldPicturePath;
                    System.out.println("oldPictureFullPath"+oldPictureFullPath);
                    File oldPictureFile = new File(oldPictureFullPath);
                    // 判断旧头像文件是否存在并删除
                    if (oldPictureFile.exists()) {
                        if (oldPictureFile.delete()) {
                            System.out.println("旧头像删除成功！");
                        } else {
                            System.out.println("旧头像删除失败！");
                        }
                    }
                }
                System.out.println("oldPicturePath:"+oldPicturePath);
                //图片的完整径
                String fullFilePath = targetFolderPath + fileName;
                System.out.println("fullFilePath+" + fullFilePath);
                //保存图片
                File destFile = new File(fullFilePath);
                profilePicture.transferTo(destFile);
                //把这个路径保存下来！
                user.setAvatarUrl(fileName);
                userService.modifyInfo(user);
                //更新之后的用户
                user = userService.selectById(user.getId());
                //把最新的⽤⼾信息设置到session中
                session.setAttribute(AppConfig.USER_SESSION, user);
                System.out.println("fullFilePath:" + fullFilePath);
                System.out.println("头像上传成功！");
                return AppResult.success();
            } catch (Exception e) {
                System.out.println("头像上传失败！");
                e.printStackTrace();
                return AppResult.failed(ResultCode.FAILED);
            }
        } else {
            System.out.println("头像上传失败！");
            return AppResult.failed(ResultCode.FAILED);
        }
    }
}
